using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    [HideInInspector]
    public Animator anim;

    public float HP;

    public float speed;
    
    private Transform Player;
    //private Animator anim;
    private SpriteRenderer sprite;

    public float attckCd = 2f;

    public GameObject bullet;

    void Start()
    {
        
        anim = GetComponent<Animator>();
        Player = GameObject.Find("Player").transform;
        //anim = GetComponent<Animator>();
        sprite = GetComponent<SpriteRenderer>();
        StartCoroutine(Attack());
    }
    void Update()
    {
        if((Player.transform.position - transform.position).normalized.x>0)
        {
            sprite.flipX = true;
        }
        else
        {
            sprite.flipX = false;
        }
        transform.position += (Player.transform.position - transform.position).normalized * speed * Time.deltaTime;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.layer == LayerMask.NameToLayer("PlayerBullet"))
        {
            Debug.Log(HP);
            StartCoroutine(behurt());
            if (HP <= 0)
            {
                getGold(100);
                gameObject.layer = LayerMask.NameToLayer("BG");
                anim.SetTrigger("Die");
            }
        }
    }
    IEnumerator behurt()
    {
        SpriteRenderer sprite = GetComponent<SpriteRenderer>();
        sprite.color = Color.red;
        yield return new WaitForSeconds(0.1f);
        sprite.color = Color.white;
    }
    public void destory()
    {
        Destroy(gameObject);
    }

    public void getGold(int x)
    {
        Data.gold += x;
        GameObject.Find("GM").GetComponent<GM>().updataGold();
        GameObject.Find("GM").GetComponent<GM>().destoryEnemy();
    }

    IEnumerator Attack()
    {
        while(true)
        {
            Vector3 attackPos = Player.transform.position - this.transform.position;
            attackPos.z = 0f;
            attackPos = attackPos.normalized;
            Instantiate(bullet, transform.position, Quaternion.identity);
            yield return new WaitForSeconds(attckCd);
        }
    }
}
